import { RouteLocationNormalizedGeneric, RouteRecordName } from "vue-router";

export const useTagViews = defineStore("tagsView", () => {
  const visitedViews = ref<RouteLocationNormalizedGeneric[]>([]);

  const cachedViews = ref<RouteRecordName[]>([]);

  const addCachedView = (view: RouteLocationNormalizedGeneric) => {
    if (cachedViews.value.includes(view.name)) {
      return;
    }

    // 将当前的name存起来
    if (!view.meta.noCache) cachedViews.value.push(view.name);
    // console.log(cachedViews.value);
  };

  const deleteCachedView = (view: RouteLocationNormalizedGeneric) => {
    const index = cachedViews.value.findIndex((v) => v === view.name);
    if (index >= 0) {
      // 直接返回
      cachedViews.value.splice(index, 1);
    }
    // console.log(cachedViews.value);
  };

  // 增
  // 需要区分那些路由时需要缓存的
  const addView = (view: RouteLocationNormalizedGeneric) => {
    // 判断是否已经存在过了
    // const exist = visitedViews.value.some((v) => v.path === view.path);
    // 此处不要用filter，性能不好
    const exist = visitedViews.value.filter((v) => v.path === view.path) || [];
    addCachedView(view);
    if (exist.length > 0) return exist;

    const newView = {
      ...view,
      title: view.meta.title //每一个页卡的名称
    };
    visitedViews.value.push(newView);
  };
  // 删
  const deleteView = (view: RouteLocationNormalizedGeneric) => {
    const index = visitedViews.value.findIndex((v) => v.path === view.path);
    if (index >= 0) {
      // 直接返回
      visitedViews.value.splice(index, 1);
    }

    deleteCachedView(view);
  };

  // 右击操作
  const delAllViews = () => {
    // 删除所有
    // 只保留固定的路由
    visitedViews.value = visitedViews.value.filter((view) => view.meta.affix);
    cachedViews.value = [];
  };

  const delOtherViews = (v: RouteLocationNormalizedGeneric) => {
    // console.log(view);
    visitedViews.value = visitedViews.value.filter(
      (view) => view.meta.affix || view.path == v.path
    );
    cachedViews.value = cachedViews.value.filter((n) => n === v.name);
  };

  return {
    visitedViews,
    addView,
    deleteView,
    cachedViews,
    deleteCachedView,
    delAllViews,
    delOtherViews
  };
});
